<template>
    <div class="cart_main" :style="ShoppingCarArr.length==0?'background-color: #fff;':'background-color: #f8f8f8;'">
        <van-nav-bar left-arrow @click-left="onClickLeft">
            <template #left>
                <van-icon :name="backicon" size="20"/>
            </template>
            <template #title>
                <span class="hometitle">购物袋</span>
            </template>
            <template #right>
                <van-icon :name="needEdit?editicon:editclose" @click="editform" size="20"/>
                <van-icon :name="messageicon" @click="toMessage" :badge="messagenum" style="margin-left:20px;margin-top:5px;"size="20"/>
            </template>
        </van-nav-bar>

        <img class="defaultpage" src="../../assets/defaultpage/shopcart.png" v-if="ShoppingCarArr.length==0" alt="">
        <div class="cart_content">
            <van-checkbox-group v-model="result" @change="checkBoxGroupChange" checked-color="#000" ref="checkboxGroup">


                <div class="cart_item_template" v-for="(item,index) in ShoppingCarArr" :key="index">
                    <div class="brand_item">
                        <van-checkbox :name="item.brand_id?`barnd#${item.brand_id}`:''" icon-size="12">
                            <div class="brand_item_brandicon" :style="{'background-image': `url(${item.brand_logo})`}"></div>
                            <span>{{item.brand_name}}</span>
                            <img src="../../assets/img/brandmore.png" alt="">
                        </van-checkbox>

                        <template v-for="(it,index) in item.data">
                            <div class="good_item">
                                <van-checkbox :name="it.id?it.id:''" icon-size="12" class="checkboxpos"/>
                                <div class="good_detail_item">
                                    <div class="good_detail_img" :style="{'background-image':`url(http://www.starrymedia.vip${it.goods.left_img})`}"></div>
                                    <div class="good_detail_info">
                                        <p>{{it.goods.brand}} {{it.goods.english_name}}</p>
                                        <p>{{it.goods.goods_name}} {{it.goods.color}}</p>
                                        <p>
                                            <span class="good_item_price"><img src="../../assets/img/money.png" alt="">{{it.goods_price}}</span>
                                            <stepper :val="it.goods_num" :cartId="it.id" @stepperMin="goodNumMin" @stepperMax="goodNumMax" class="basestepper"/>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>


            </van-checkbox-group>
        </div>


        <div class="count_info" v-if="!ShoppingCarArr.length==0">
            <div class="count_checkall">
                <van-checkbox v-model="checked" checked-color="#000" @change="SelectAll" icon-size="12">全选</van-checkbox>
            </div>
            <div class="count-item" v-if="needEdit">
                <span class="count_price"><img src="../../assets/img/money.png" alt="">{{goodPriceCount}}</span>
            </div>
        </div>
        
        <div v-if="!ShoppingCarArr.length==0" class="cartbtn">
            <img :src="needEdit?result.length>0?Submitbtn:SubmitbtnDea:result.length>0?delActivebtn:delbtn" class="countbtn" @click="changeCar" alt="">
        </div>
        <img v-if="ShoppingCarArr.length==0" src="../../assets/defaultpage/gooddetail-btn.png" class="countbtn" @click="gotolook" alt="">
    </div>
</template>
<script>
import stepper from '../../components/stepper'
import {_getUserCart,_changeCartGoodsNum,_cartDel} from '../../service/shopcart.js'
import {_getUserMessage} from '../../service/user'
export default {
    data(){
        return{
            backicon:require('../../assets/img/backicon.png'),
            editicon:require('../../assets/img/editicon.png'),
            editclose:require('../../assets/img/editclose.png'),
            messageicon:require('../../assets/img/messageicon.png'),
            messagenum:0,
            ShoppingCarArr:[],
            result:[],
            resultTemplate:[],
            val:1,
            checked:false,//全选是否选中
            needEdit:true,//是否处于编辑状态，默认结算
            ArrPriceCount:0,
            goodPriceCount:0,


            needAll:false,//
            Submitbtn:require('../../assets/img/toSettle.png'),
            SubmitbtnDea:require('../../assets/img/toSettlenull.png'),
            delbtn:require('../../assets/img/toDel.png'),
            delActivebtn:require('../../assets/img/toDelActive.png'),

            brandicon1:require("../../assets/img/brand1.png"),
            brandicon2:require("../../assets/img/brand2.png"),
            gooddetail:"http://www.starrymedia.vip/public/upload/goods/2020/04-20/0f5dde891cbba220c470d43fa842171f.png",
        }
    },
    components:{
        stepper
    },
    created(){
        this.getUserShoppingCart()
        this.getUserMessage()
    },
    methods:{
        gotolook(){
            this.$router.push('/indexs')
        },
        getUserMessage(){
            let _this=this
            let uid=JSON.parse(localStorage.getItem("user")).user_id
            _getUserMessage({
                user_id:uid
            }).then(res=>{
                console.log(res)
                if(res.errcode==1){
                    _this.messagenum=res.data.filter(item=>{return item.status==0}).length
                }
            })
        },
        onClickLeft(){
            if(localStorage.getItem("routerHistory")=="/cartorder" ||localStorage.getItem("routerHistory")=="/MsgList"){
                this.$router.push("/indexs")
            }else{
                this.$router.go(-1)
            }
            
        },
        editform(){
            this.$refs.checkboxGroup.toggleAll(false);
            this.needEdit=!this.needEdit
            this.CalcPrice()
        },
        toMessage(){
            localStorage.setItem("MessageList","/shopcart")
            this.$router.push("/MsgList")
        },
        SelectAll(info){
            //全选
            if(info){
                this.$refs.checkboxGroup.toggleAll(true);
            }else{
                this.$refs.checkboxGroup.toggleAll();
            }
            this.CalcPrice()
        },
        CalcPrice(){
            let pricecounr=0
            for(let ff=0;ff<this.result.length;ff++){
                if(typeof this.result[ff]=="number"){
                    for(let i=0;i<this.ShoppingCarArr.length;i++){
                        let goodArr=this.ShoppingCarArr[i]
                        for(let h=0;h<goodArr.data.length;h++){
                            if(goodArr.data[h].id==this.result[ff]){
                                pricecounr+=Number(goodArr.data[h].goods_price)*goodArr.data[h].goods_num
                            }
                        }
                    }
                }
            }
            this.goodPriceCount = pricecounr
        },
        checkBoxGroupChange(data){
            let _this=this
            if(data.length<this.resultTemplate.length){
                for(let z=0;z<this.resultTemplate.length;z++){
                    if(!data.some(item=>{return item==this.resultTemplate[z]})){
                        for(let i=0;i<this.ShoppingCarArr.length;i++){
                            let goodArr=this.ShoppingCarArr[i]
                            for(let h=0;h<goodArr.data.length;h++){
                                if(goodArr.data[h].id==_this.resultTemplate[z]){
                                    let brandid="barnd#"+goodArr.brand_id
                                    let pot=_this.result.indexOf(brandid)
                                    if(pot>-1){
                                        _this.result.splice(pot,1)
                                    }
                                    
                                }
                            }
                        }
                    }
                }
                
            }else{
                for(let i=0;i<data.length;i++){
                    if(typeof data[i]=="string"){
                        //品牌
                        let brandid=Number(data[i].split("#")[1])
                        // console.log("brand",brandid)
                        let goodArr=this.ShoppingCarArr.filter(item=>{return item.brand_id==brandid})[0].data
                        // console.log(goodArr)
                        goodArr.forEach(el => {
                            if(!this.result.some(item=>{return item==el.id})){
                                this.result.push(el.id)
                            }
                        });

                    }
                    if(typeof data[i]=="number"){
                        //单个商品
                    }
                }
            }
            
            this.CalcPrice()
            this.resultTemplate=[]
            this.resultTemplate=[].concat(this.result)

        },
        goodNumMin(id,val){//商品数量减一
            let _this=this
            if(val<2){
                return
            }
            _this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
            })           
            _changeCartGoodsNum({
                cart_id:id,
                goods_num:val-1
            }).then(res=>{
                console.log(res)
                setTimeout(()=>{
                    _this.$toast.clear()
                    if(res.errcode==1){
                        _this.$toast("取消成功")
                    }else{
                        _this.$toast("取消失败")
                    }
                    _this.getUserShoppingCart()
                },1000)
            })
        },
        goodNumMax(id,val){//商品数量加一
            let _this=this
            _this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
            })           
            _changeCartGoodsNum({
                cart_id:id,
                goods_num:val+1
            }).then(res=>{
                console.log(res)
                setTimeout(()=>{
                    _this.$toast.clear()
                    if(res.errcode==1){
                        _this.$toast("添加成功")
                    }else{
                        _this.$toast("添加失败")
                    }
                    _this.getUserShoppingCart()
                },1000)
            })
        },
        getUserShoppingCart(){
            let _this=this
			if(localStorage.getItem('user')==null||localStorage.getItem('user')==undefined){
				return
			}
			_getUserCart().then(res=>{
				_this.ShoppingCarArr=[]
                _this.ShoppingCarArr.push(...res.data)
                console.log(_this.ShoppingCarArr)
                if(_this.ShoppingCarArr.length>0){
                   _this.CalcPrice() 
                }
			})
        },
        changeCar(){
            let _this=this
            
            if(this.needEdit){
                if(localStorage.getItem('user')==null||localStorage.getItem('user')==undefined){
                    this.$router.push('/login')
                    return
                }

                let Obj={}
                Obj.user_id=JSON.parse(localStorage.getItem("user")).user_id
                Obj.cart_id=this.result.filter(item=>{return typeof item=="number"}).join(",")
                Obj.order_amount=this.goodPriceCount
                localStorage.setItem("CartOrder",JSON.stringify(Obj))
                this.$router.push("/cartorder")


            }else{
                if(this.result.length==0){
                    return
                }
                _this.$toast.loading({
                    duration: 0, // 持续展示 toast
                    forbidClick: true,
                })
                _cartDel(
                    this.result.filter(item=>{return typeof item=="number"}).join(",")
                ).then(res=>{
                    console.log(res)
                    setTimeout(()=>{
                        _this.$toast.clear()
                        // if(res.errcode==1){
                        //     _this.$toast("删除成功")
                        // }else{
                        //     _this.$toast("删除失败")
                        // }
                        _this.getUserShoppingCart()
                    },1000)
                })
            }
        }
    }
}
</script>
<style lang="less" scoped>
.cart_main{
    width: 100%;
    height: 100vh;
    overflow-y: auto;

    .hometitle{
        font-size: 18px;
        font-family: "PingFang SC","Microsoft YaHei";
        font-weight: bold;
        color: #000;
        line-height: 44px;
        text-align: center;
    }
    /deep/.van-nav-bar{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
    }
    /deep/.van-info{
        top: 5px !important;
    }
    .defaultpage{
        width: 97px;
        position: absolute;
        top: 30%;
        left: 37%;
    }
    .cart_content{
        width: 100%;
        height: auto;
        padding-bottom: 50px;
        padding-top: 46px;
        // overflow-y: auto;
        // @media only screen and (min-device-height: 500px) and (max-device-height: 690px) {
        //     height: 440px;
        // }
        // @media only screen and (min-device-height: 691px) and (max-device-height: 1200px){
        //     height: 580px;
        // }
        // @media only screen and (min-device-height: 720px) and (max-device-height: 760px){
        //     height: 470px;
        // }
        .cart_item_template{
            width: 100%;
            height: auto;
            background-color: #fff;
            padding-left: 17px;
            padding-right: 17px;
            margin-top: 6px;
            .brand_item{
                width: 100%;
                height: auto;
                .brand_item_brandicon{
                    width: 24px;
                    height:45px;
                    margin-left: 8px;
                    background-position: center;
                    background-repeat: no-repeat;
                    background-size: contain;
                    float: left;
                }
                span{
                    line-height: 45px;
                    font-family: "DINPro-Bold";
                    font-size: 12px;
                    color: #333;
                    float: left;
                    margin-left: 10px;
                }
                img{
                    display: inline-block;
                    width: 6px;
                    margin-left: 10px;
                    margin-top: 18px;
                    float: left;
                }
                .checkboxpos{
                    width: 12px;
                    height: 85px;
                    display: inline-block;
                    padding-top: 24px;
                }
                .good_item{
                    width: 100%;
                    height: auto;
                    .good_detail_item{
                        height: 85px;
                        width: 316px;
                        float: right;
                        margin-left: 10px;
                        .good_detail_img{
                            display: inline-block;
                            width: 90px;
                            height: 85px;
                            background-position: center top;
                            background-repeat: no-repeat;
                            background-size: contain;
                            vertical-align: super;
                        }
                        .good_detail_info{
                            display: inline-block;
                            width: 210px;
                            height: 85px;
                            float: right;
                            margin-left: 10px;
                            p{
                                margin-bottom: 0;
                                font-family: "PingFang SC","Microsoft YaHei";
                                font-size: 12px;
                                color: #999;
                                text-overflow: ellipsis;
                                overflow: hidden;
                                white-space: nowrap;
                                &:first-child{
                                    margin-top: 9.5px;
                                }
                                .good_item_price{
                                    display: inline-block;
                                    margin: 0;
                                    font-family: "DINPro-Bold";
                                    font-size: 15px;
                                    color: #000;
                                    img{
                                        display: inline-block;
                                        width: 8px;
                                        margin: 0 5px 0 0;
                                        float: none;    
                                        vertical-align: baseline;
                                    }
                                }
                                .basestepper{
                                    float: right;
                                    margin-top: 10px;
                                }
                            }
                        }
                    }
                }
                

            }
        }
    }

    .count_info{
        width: 100%;
        height: 41px;
        background-color: #fff;
        padding:15px;
        position: fixed;
        z-index: 50;
        bottom: 90px;
        left: 0;
        right: 0;
        .count_checkall{
            width: 30%;
            float: left;
        }
        .count-item{
            width: 30%;
            float: right;
            .count_price{
                display: inline-block;
                margin: 0;
                font-family: "DINPro-Bold";
                font-size: 15px;
                color: #000;
                float: right;
                line-height: 10px;
                img{
                    display: inline-block;
                    width: 8px;
                    margin: 0 5px 0 0;
                    float: none;    
                    vertical-align: baseline;
                }
            }
        }
    }
    .cartbtn{
        width: 100%;
        height: 90px;
        background-color: #f8f8f8;
        position: fixed;
        bottom: 0;
        left: 0;
        z-index: 10;
        .countbtn{
            display: block;
            width: 367px;
            // margin: 5px auto 0 auto;
            position: fixed;
            bottom: 20px;
            left: 4px;
            right: 4px;
        }
    }
    .countbtn{
        display: block;
        width: 367px;
        // margin: 5px auto 0 auto;
        position: fixed;
        bottom: 20px;
        left: 4px;
        right: 4px;
    }
}
</style>